import React, { useEffect, useState } from 'react';
import { Input, Button, Menu, Select } from 'antd';
import styles from './style.less';
import BookItem from './components/BookItem/BookItem';
import { SearchOutlined } from '@ant-design/icons';
import { Get_All_Book, Get_Book_ByInfo } from '@/services/api';

function Home() {
  const [keyWordTemp, setKeyWordTemp] = useState('');
  const [keyWord, setKeyWord] = useState('');
  const [type, setType] = useState('');
  const [order, setCurrent] = useState('order0');
  const [flag, setFlag] = useState(1);

  function handleClick(e: any) {
    setCurrent(e.key);
    console.log(order);
  }

  const [bookList, setBookList] = useState([]);

  function handleType(value: any) {
    setType(value);
  }

  function search() {
    setKeyWord(keyWordTemp);
  }

  useEffect(() => {
    try {
      Get_Book_ByInfo(keyWord, type, order).then(res => {
        console.log(res);
        setBookList(res);
      });
    } catch (error) {
      console.log(error);
    }
  }, [type, order, keyWord]);

  const books = bookList.map(item => <BookItem source={item} />);

  function keyWordChanged(e: any) {
    setKeyWordTemp(e.target.value);
  }

  if (flag === 1) {
    try {
      Get_All_Book().then(res => {
        console.log(res);
        setFlag(0);
        setBookList(res);
      });
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <div className={styles.outer}>
      <div className={styles.main}>
        <div className={styles.searchblock}>
          <Input
            placeholder="输入书名"
            value={keyWordTemp}
            size="large"
            onChange={keyWordChanged}
          />
          <Button size="large" type="primary" onClick={search}>
            <SearchOutlined />
          </Button>
        </div>

        <div className={styles.typeblock}>
          <h2>选择书籍分类：</h2>
          <Select onChange={handleType} placeholder="请选择书籍类型">
            <Select.Option value="医学">医学</Select.Option>
            <Select.Option value="计算机">计算机</Select.Option>
            <Select.Option value="艺术">艺术</Select.Option>
            <Select.Option value="历史">历史</Select.Option>
            <Select.Option value="外语">外语</Select.Option>
            <Select.Option value="经济">经济</Select.Option>
            <Select.Option value="">全部</Select.Option>
          </Select>
        </div>
        <div className={styles.paddinghead}>
          <Menu onClick={handleClick} selectedKeys={[order]} mode="horizontal">
            <Menu.Item key="order0">默认排序</Menu.Item>
            <Menu.Item key="order1">价格降序</Menu.Item>
            <Menu.Item key="order2">价格升序</Menu.Item>
            <Menu.Item key="order3">最近发布</Menu.Item>
          </Menu>
        </div>
        <div className={styles['book-container']}>{books}</div>
      </div>
    </div>
  );
}

export default Home;
